import { IFeidaoAiBrowserComponent } from '@dfeidao/atom-web/interfaces';

import get from '@dfeidao/atom-web/local/get';
import remove from '@dfeidao/atom-web/local/remove';
import fire from '@dfeidao/atom-web/msg/fire';
import nodejs from "@dfeidao/atom-web/msg/nodejs";
import error from '@dfeidao/atom-web/msgbox/error';
import success from '@dfeidao/atom-web/msgbox/success';
import s_get from '@dfeidao/atom-web/storage/get';

export default async function a002(fd: IFeidaoAiBrowserComponent) {

	const usercode = get(fd, 'ucode');

	const prid = await s_get('productid');

	const create_time = new Date().getTime();
	let staff_no = get(fd, 'staff_no');
	const staff_name = fd.data.node.querySelector<HTMLInputElement>('#name').value;
	const role_no = fd.data.node.querySelector<HTMLSelectElement>('#name2').value;
	if (!staff_no) {
		staff_no = '';
	}
	if (!role_no) {
		error('关联角色为空');
		return;
	}
	const query2 = {
		filter: {
			productid: prid,
			usercode
		}
	};
	//
	const res2 = await nodejs<{ dataArray: Array<{ role_no: string }> }>('consumer/zj-000005/consumer-find4', query2);
	const r_no = res2.dataArray.map((v) => {
		return v.role_no;
	});
	if (r_no.indexOf(role_no) !== -1) {
		error('角色编号不能重复');
		fd.data.node.querySelector<HTMLInputElement>('#name').value = '';
		remove(fd, 'staff_no');
		return;
	}


	const query = {
		usercode,
		role_no,
		pk_val: staff_no,
		search_field_val: staff_name,
		create_time,
		productid: prid
	};

	const res = await nodejs('consumer/zj-000005/consumer-add1', query);
	if (res === 'success') {
		fire('zj-000004', 'ec-002', usercode);
		remove(fd, 'staff_no');
		remove(fd, 'role_no');
		fd.data.node.classList.add('display-n');
		success('保存成功');
	} else {
		error('保存失败');
	}
}
